package com.example.gitclient.ui;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.gitclient.R;
import com.example.gitclient.adapter.BranchAdapter;
import com.example.gitclient.git.GitManager;
import com.example.gitclient.model.Branch;
import com.example.gitclient.model.Repository;
import com.example.gitclient.utils.RepositoryManager;

import org.eclipse.jgit.api.errors.GitAPIException;

import java.io.IOException;
import java.util.List;

/**
 * 分支管理界面，显示分支列表
 */
public class BranchActivity extends AppCompatActivity implements BranchAdapter.OnBranchClickListener {
    private RecyclerView recyclerBranches;
    private TextView tvRepositoryName;
    private TextView tvCurrentBranch;

    private Repository repository;
    private GitManager gitManager;
    private RepositoryManager repositoryManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_branch);

        // 初始化视图
        recyclerBranches = findViewById(R.id.recyclerBranches);
        tvRepositoryName = findViewById(R.id.tvRepositoryName);
        tvCurrentBranch = findViewById(R.id.tvCurrentBranch);
        
        recyclerBranches.setLayoutManager(new LinearLayoutManager(this));

        // 获取仓库路径
        String repositoryPath = getIntent().getStringExtra("repository_path");
        if (repositoryPath == null) {
            Toast.makeText(this, R.string.repository_not_found, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化仓库管理器
        repositoryManager = new RepositoryManager(this);

        // 加载仓库
        loadRepository(repositoryPath);

        // 设置创建分支按钮点击事件
        findViewById(R.id.btnCreateBranch).setOnClickListener(v -> showCreateBranchDialog());
    }

    /**
     * 加载仓库
     * @param repositoryPath 仓库路径
     */
    private void loadRepository(String repositoryPath) {
        // 查找仓库
        for (Repository repo : repositoryManager.getRepositories()) {
            if (repo.getPath().equals(repositoryPath)) {
                repository = repo;
                break;
            }
        }

        if (repository == null) {
            Toast.makeText(this, R.string.repository_not_found, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 打开Git仓库
        try {
            gitManager = new GitManager(repository);
            updateUI();
            loadBranches();
        } catch (IOException e) {
            Toast.makeText(this, getString(R.string.failed_to_open_repository) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
            finish();
        }
    }

    /**
     * 更新UI
     */
    private void updateUI() {
        tvRepositoryName.setText(repository.getName());
        tvCurrentBranch.setText(getString(R.string.current_branch) + ": " + repository.getCurrentBranch());
    }

    /**
     * 加载分支列表
     */
    private void loadBranches() {
        try {
            List<Branch> branches = gitManager.getBranches();
            BranchAdapter branchAdapter = new BranchAdapter(branches, this);
            recyclerBranches.setAdapter(branchAdapter);
        } catch (GitAPIException e) {
            Toast.makeText(this, getString(R.string.failed_to_load_branches) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 显示创建分支对话框
     */
    private void showCreateBranchDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_create_branch, null);
        EditText etBranchName = dialogView.findViewById(R.id.etBranchName);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.create_branch)
                .setView(dialogView)
                .setPositiveButton(R.string.create, (dialog, which) -> {
                    String branchName = etBranchName.getText().toString().trim();

                    if (branchName.isEmpty()) {
                        Toast.makeText(this, R.string.please_enter_branch_name, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    createBranch(branchName);
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 创建分支
     * @param branchName 分支名称
     */
    private void createBranch(String branchName) {
        try {
            gitManager.createBranch(branchName);
            Toast.makeText(this, R.string.branch_created_successfully, Toast.LENGTH_SHORT).show();
            loadBranches();
        } catch (GitAPIException e) {
            Toast.makeText(this, getString(R.string.create_branch_failed) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onBranchClick(Branch branch) {
        // 如果点击的是当前分支，不做任何操作
        if (branch.isCurrent()) {
            return;
        }

        // 显示确认对话框
        new AlertDialog.Builder(this)
                .setTitle(R.string.checkout_branch)
                .setMessage(getString(R.string.checkout_branch_confirm, branch.getName()))
                .setPositiveButton(R.string.checkout, (dialog, which) -> checkoutBranch(branch.getName()))
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 切换分支
     * @param branchName 分支名称
     */
    private void checkoutBranch(String branchName) {
        try {
            gitManager.checkoutBranch(branchName);
            Toast.makeText(this, R.string.branch_checkout_successful, Toast.LENGTH_SHORT).show();
            updateUI();
            loadBranches();
        } catch (GitAPIException e) {
            Toast.makeText(this, getString(R.string.branch_checkout_failed) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (gitManager != null) {
            gitManager.close();
        }
    }
}